package opl.utilities;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;

public class AsyncServiceHelper extends AsyncTask<Void, Void, HttpResponse> {

	private MethodType methodType;
	private String jsonData;
	private String serviceUri;

	public AsyncServiceHelper(String serviceUri, MethodType methodType,
			String jsonData) {
		this.serviceUri = serviceUri;
		this.methodType = methodType;
		this.jsonData = jsonData;
	}

	@Override
	protected HttpResponse doInBackground(Void... params) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse response = null;

		if (methodType == MethodType.GET) {
			HttpGet getRequest = new HttpGet(serviceUri);
			try {
				response = httpclient.execute(getRequest);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (methodType == MethodType.POST) {
			HttpPost postRequest = new HttpPost(serviceUri);
			try {
				StringEntity se = new StringEntity(jsonData);
				postRequest.setHeader("Accept", "application/json");
				postRequest.setHeader("Content-type", "application/json");
				postRequest.setEntity(se);
				response = httpclient.execute(postRequest);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return response;
	}

}
